package com.hongkuncheng.cms.controller.admin;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.util.FileCopyUtils;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.FileHelper;
import com.hongkuncheng.cms.helper.PageHelper;
import com.hongkuncheng.cms.model.Webinfo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 模板管理
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/template")
public class AtemplateController extends BaseController {

    // 模板列表
    @RequestMapping
    public String index() {
        webinfo = factorySession.get(Webinfo.class, 1);
        request.setAttribute("webinfo", webinfo);
        String templatePath = applicationDirectory + "/template";
        List<File> templates = FileHelper.getDirectorys(templatePath);
        request.setAttribute("templates", templates);
        File skin = new File(templatePath + "/" + webinfo.getTemplate() + "/skins");
        request.setAttribute("setskin", skin.exists());
        String grayCssFileContent = FileHelper.Read(applicationDirectory + "/resource/css/grayscale.css");
        request.setAttribute("grayscale", !grayCssFileContent.equals(""));
        return view();
    }

    // 一键转灰
    @RequestMapping("switchgray")
    @ResponseBody
    public void switchgray() {
        checkAdminPermission("yunwei_webmaintain_template");
        File grayCssFile = new File(applicationDirectory + "/resource/css/grayscale.css");
        String grayCssFileContent = FileHelper.Read(grayCssFile);
        String color = "";
        if (!grayCssFileContent.equals("")) {
            FileHelper.write(grayCssFile, "");
            color = "原（彩）";
        } else {
            FileHelper.write(grayCssFile, "*{\n" +
                    "\tfilter: grayscale(100%);\n" +
                    "    -webkit-filter: grayscale(100%);\n" +
                    "    -moz-filter: grayscale(100%);\n" +
                    "    -ms-filter: grayscale(100%);\n" +
                    "    -o-filter: grayscale(100%);\n" +
                    "    filter: url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'><filter id='grayscale'><feColorMatrix type='matrix' values='0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0'/></filter></svg>#grayscale\");\n" +
                    "    filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);\n" +
                    "    -webkit-filter: grayscale(1);\n" +
                    "}");
            color = "灰";
        }
        PageHelper.alertAndRedirect("转换成功，已装网页色调转换为" + color + "色。", "./");
    }

    // 模板切换
    @RequestMapping("change")
    @ResponseBody
    public void change() {
        checkAdminPermission("yunwei_webmaintain_template");
        webinfo = factorySession.get(Webinfo.class, 1);
        webinfo.setTemplate(request.getParameter("template"));
        PageHelper.alertAndRedirect("切换成功，请重新生成相关静态页面。", "./");
    }

    // 模板编辑
    @RequestMapping("edit")
    public String edit() {
        String template = request.getParameter("template");
        request.setAttribute("template", template);
        return view();
    }

    // 模板编辑处理
    @RequestMapping("editdo")
    @ResponseBody
    public void editdo() {
        checkAdminPermission("yunwei_webmaintain_template");
        String newName = request.getParameter("name");
        String newFilePath = applicationDirectory + "/template/" + newName;
        File newFile = new File(newFilePath);
        if (newFile.exists()) {
            PageHelper.alertAndGoBack("该文件夹名已存在，请重新输入");
            return;
        }
        String oldName = request.getParameter("oldname");
        if (oldName == "") {
            // 新建
            newFile.mkdir();
        } else {
            // 更新
            String oldFilePath = applicationDirectory + "/template/" + oldName;
            File oldFile = new File(oldFilePath);
            oldFile.renameTo(newFile);
        }
        PageHelper.alertAndRedirect("保存成功", "./");
    }

    // 模板删除
    @RequestMapping("delete")
    @ResponseBody
    public void delete() {
        checkAdminPermission("yunwei_webmaintain_template");
        String template = request.getParameter("template");
        String filePath = applicationDirectory + "/template/" + template;
        FileHelper.deleteDir(filePath);
        PageHelper.alertAndRedirect("删除成功", "./");
    }

    // 更换皮肤
    @RequestMapping("skin")
    public String skin() {
        webinfo = factorySession.get(Webinfo.class, 1);
        request.setAttribute("webinfo", webinfo);
        String templatePath = applicationDirectory + "/template";
        List<File> skins = FileHelper.getDirectorys(templatePath + "/" + webinfo.getTemplate() + "/skins");
        request.setAttribute("skins", skins);
        return view();
    }

    // 更换皮肤提交
    @RequestMapping("skinchange")
    @ResponseBody
    public void skinchange() throws Exception {
        checkAdminPermission("yunwei_webmaintain_template");
        String skin = request.getParameter("skin");
        if (skin != "") {
            webinfo = factorySession.get(Webinfo.class, 1);
            String templatePath = applicationDirectory + "/template";
            List<File> fileinfos = FileHelper.getAllFiles(templatePath + "/" + webinfo.getTemplate() + "/skins/" + skin);
            for (File file : fileinfos) {
                if (!file.getAbsolutePath().replace("\\", "/").endsWith("/template/" +
                        webinfo.getTemplate() + "/skins/" + skin + "/cover.jpg")) {
                    File destFile = new File(file.getAbsolutePath()
                            .replace("\\", "/").replace("/skins/" + skin, ""));
                    FileOutputStream os = new FileOutputStream(destFile);
                    FileSystemResource resource = new FileSystemResource(file.getAbsoluteFile());
                    FileCopyUtils.copy(resource.getInputStream(), os);
                }
            }
            if (webinfo.getSkin() != skin) webinfo.setSkin(skin);
            PageHelper.alertAndRedirect("更换成功", "./");
        } else {
            PageHelper.alertAndGoBack("请选择一项皮肤");
        }
    }

}
